package com.hisoft.xml;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.hisoft.exception.XpathNotFoundException;

/***
 * 
 * <b> </b>
 * 
 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
 */
public class Dom4JXMLHelper {
	static Logger logger = Logger.getLogger(Dom4JXMLHelper.class);
	private static SAXReader saxReader = new SAXReader();

	/**
	 * 返回docunment对象
	 * <b> </b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
	 */
	private static Document read(String filePath) {
		try {
			return saxReader.read(filePath);
		} catch (DocumentException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 根据参数获得NODE的集合
	 * <b> </b>
	 * @param xpath xpath路径
	 * @param filePath 文件路径
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
	 */
	public static List<?> readNodeList(String xpath, String filePath) throws XpathNotFoundException {
		List<?> list = read(filePath).selectNodes(xpath);
		if (list.size() == 0)
			throw new XpathNotFoundException(xpath, filePath);
		else
			return list;
	}

	/**
	 * 根据参数获得NODE的字符串集合
	 * <b> </b>
	 * @param xpath xpath路径
	 * @param filePath 文件路径
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
	 */
	public static List<String> getTextList(String xpath, String filePath) throws XpathNotFoundException {
		List<?> nodeList = readNodeList(xpath, filePath);
		List<String> msgList = new ArrayList<String>();
		for (Object node : nodeList) {
			msgList.add(((Node) node).getText());
		}
		return msgList;
	}

	/**
	 * 根据参数获得第一个NODE的
	 * <b> </b>
	 * @param xpath xpath路径
	 * @param filePath 文件路径
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
	 */
	public static Node readSingleNode(String xpath, String filePath) {
		Node node = read(filePath).selectSingleNode(xpath);
		if (node == null) {
			XpathNotFoundException e = new XpathNotFoundException(xpath, filePath);
			throw e;
		} else
			return node;
	}
}
